package cn.neusoft.interceptor;

import cn.neusoft.vo.ResultBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 管理员前端的登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        System.out.println("-----登录验证-----" + session.getId());
        ;
        Object adminUser = session.getAttribute("adminUser");
        if (adminUser == null) {

            //将失败的ResultBean转成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(ResultBean.ERROR(50001, "未登录"));


            //设置响应数据的类型和编码  写出去
            response.setContentType("application/json;charset=UTF_8");
            ;
            response.getWriter().write(json);

            //不放行
            return false;
        }

        //放行
        return true;
    }
}
